package fox.framework.rpc.endpoint.netty.heartbeat;

import fox.framework.rpc.client.heartbeat.Ping;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

import java.util.List;

/**
 * @author cuichao
 * @Description: RpcHeartBeatDecode
 * @Date: create in 2020/4/22 21:52
 */
public class RpcHeartBeatDecode extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        //获取长度
        byte[] bytes = new byte[4];
        //获取内容
        in.readBytes(bytes);
        String ping = new String(bytes,CharsetUtil.UTF_8);

        if(Ping.PING.equals(ping) || Ping.PONG.equals(ping)){
            out.add(new Ping(ping));
        }else{
            /**
             * 不是心跳由下个读取处理器处理
             * 由于编解码器使用后会回收对象
             * 所以进行引用计数+1,byteBuf
             * 的ReadIndex复位
             */
            ReferenceCountUtil.retain(in);
            in.resetReaderIndex();
            ctx.fireChannelRead(in);
        }
    }

}
